package com.manong.bookstore.user.util;

import com.manong.bookstore.user.feign.UserFeignService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class UserSessionTool {
	public static Integer getUserId(UserFeignService userFeignService, HttpServletRequest request) {
		Cookie cookie = CookieFinder.findCookie(request, "USERSESSION");

		if(cookie != null) {
			Map<String, Object> result = userFeignService.info(cookie.getValue());

			if(result != null) {
				result = (Map<String, Object>)result.get("session");

				if(result != null) {
					result = (Map<String, Object>)result.get("attrs");

					if(result != null && result.get("userId") != null) {
						String userId = result.get("userId").toString();

						return userId != null ? new Integer(userId) : null;
					}
				}
			}
		}

		return null;
	}

	public static String getUserName(UserFeignService userFeignService, HttpServletRequest request) {
		Cookie cookie = CookieFinder.findCookie(request, "USERSESSION");

		if(cookie != null) {
			Map<String, Object> result = userFeignService.info(cookie.getValue());

			if(result != null) {
				result = (Map<String, Object>)result.get("session");

				if(result != null) {
					result = (Map<String, Object>)result.get("attrs");

					if(result != null && result.get("userName") != null) {
						String userName = result.get("userName").toString();

						return userName != null ? userName : null;
					}
				}
			}
		}

		return null;
	}
}
